import { Injectable, OnModuleInit } from "@nestjs/common";
import { MongoService } from "./mongo.service";
import { resolve } from "node:path/win32";
import dayjs from 'dayjs'
import { threadId } from "worker_threads";
import { RedisService } from "./redis.service";

const WXID_TO_USER_PRIFIX = 'WXID2USER:'

@Injectable()
export class StorageService implements OnModuleInit {

    timestamp: number = 0
    msgs: object[] = []
    lastMsg: string = null

    constructor(
        private mongoService: MongoService,
        private redisService: RedisService
    ) { }

    onModuleInit() {

    }

    async getMessageSinceTime(conversationID : any,timestamp: number) {

        let res = await this.mongoService.msgColl.aggregate([
            {
                $match: { doc_id: "si_2062181717_8171668571" }
            },
            {
                $project: {
                    _id: 0,
                    newests: {
                        $slice: [{
                            $sortArray: {
                                input: {
                                    $filter: {
                                        input: "$msgs",
                                        as: 'msg',
                                        cond: {
                                            $gt: ['$$msg.Data.MsgSeq', timestamp]
                                        }
                                    },

                                },
                                sortBy: {
                                    "Data.MsgSeq": 1
                                }
                            }
                        }, -10]
                    },
                    // 使用$arrayElemAt获取数组指定索引的元素
                    forwardIndex: {
                        $mod: [{ $subtract: ['$forwardIndex', 1] }, "$maxBufferLen"]
                    },
                    backIndex: 1,
                    max: {
                        $let: {
                            vars: {
                                indexRaw: {
                                    $mod: [{ $subtract: ['$forwardIndex', 1] }, "$maxBufferLen"]
                                }
                            },
                            in: {
                                $arrayElemAt: ["$msgs", "$$indexRaw"] // 获取数组的第一个元素
                                //$multiply : ["$$indexRaw" , 1]
                            }
                        },
                    },
                    min: {
                        $arrayElemAt: ["$msgs", "$backIndex"] // 获取数组的第一个元素
                    }

                }
            }])
            .toArray()

        return res
    }

    async setWxid2UserID(wxid,user_id){
        await this.redisService.redis().set(`${WXID_TO_USER_PRIFIX}${wxid}`,user_id)
    }

    async getUserIDByWxid(wxid) {
        return await this.redisService.redis().get(`${WXID_TO_USER_PRIFIX}${wxid}`)
    }
}